package com.example.oop;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

/**
 * @author houyangfan
 * @version 1.0
 * @date 2022/8/2 18:25
 */
public class FanxingBug extends FanxingParent<String>{

    @Override
    public void setValue(String value) {
        System.out.println("Child1.setValue called");
        super.setValue(value);
    }

    //
    public static void main(String[] args) {
        right();
    }

    /**
     * 输出结果：
     * Child1.setValue called
     * Parent.setValue called
     * Parent.setValue called
     * value: test updateCount: 2
     *
     * parent中被调用了两次
     */
    public static void wrong(){
        FanxingBug child = new FanxingBug();
        Arrays.stream(child.getClass().getMethods())
                .filter(method -> method.getName().equals("setValue"))
                .forEach(method -> {
                    try {
                        method.invoke(child, "test");
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                });
        System.out.println(child.toString());
    }

    public static void right(){
        FanxingBug child = new FanxingBug();
        Arrays.stream(child.getClass().getDeclaredMethods())
                .filter(method -> method.getName().equals("setValue"))
                .forEach(method -> {
                    try {
                        method.invoke(child, "test");
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                });
        System.out.println(child.toString());
    }
}
